<template>
  <div class="backG">
    <div class="login">
      <h3>叩丁狼商品管理系统</h3>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item prop="username">
          <el-input
            placeholder="请输入账号"
            v-model="ruleForm.username"
            type="text"
            autocomplete="off"
          >
            <template #prefix>
              <el-icon :size="24"><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="ruleForm.password"
            type="password"
            autocomplete="off"
            placeholder="请输入密码"
          >
            <template #prefix>
              <el-icon :size="24"><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from "element-plus";
import { loginApi } from "./api";
import { reactive, ref } from "vue";
import type { FormInstance } from "element-plus";
import { User, Lock } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
const router = useRouter();

const ruleFormRef = ref<FormInstance>();

const validatePass = (rule: any, value: string, callback: any) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else {
    callback();
  }
};

const ruleForm = reactive({
  username: "",
  password: "",
});

const rules = reactive({
  username: [{ required: true, message: "请输入账号", trigger: "blur" }],
  password: [{ validator: validatePass, trigger: "blur" }],
});

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      //valid是true代表数据校验通过，下一步就是发请求
      loginApi(ruleForm).then((res) => {
        if (res.code === 200) {
          localStorage.setItem("token", res.data.tokenHead + res.data.token);
          ElMessage.success("登陆成功");
          router.push("/");
        }
      });
      console.log(ruleForm);
    } else {
      console.log("error submit!");
      //valid为false需要提示用户
      ElMessage.error("请输入信息");
      return false;
    }
  });
};
</script>

<style scoped lang="less">
.backG {
  width: 100%;
  height: 100vh;
  background-color: #2d3a4b;
  position: relative;
}
.login {
  position: absolute;
  width: 400px;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  h3 {
    text-align: center;
    margin-bottom: 25px;
    color: #fff;
  }
  :deep(.el-input__inner) {
    height: 50px;
  }
  :deep(.el-button--primary) {
    width: 100%;
  }
}
</style>
